package com.example.backend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.backend.common.api.ResultCode;
import com.example.backend.common.exception.BusinessException;
import com.example.backend.dto.PermissionDTO;
import com.example.backend.entity.Permission;
import com.example.backend.entity.RolePermission;
import com.example.backend.mapper.PermissionMapper;
import com.example.backend.mapper.RolePermissionMapper;
import com.example.backend.service.PermissionService;
import com.example.backend.common.tree.MenuTree;
import com.example.backend.common.tree.TreeBuilder;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 权限服务实现类
 */
@Service
@RequiredArgsConstructor
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission> implements PermissionService {
    
    private final RolePermissionMapper rolePermissionMapper;
    private final TreeBuilder treeBuilder;
    
    @Override
    public List<Permission> getUserPermissions(Long userId) {
        return baseMapper.selectUserPermissions(userId);
    }
    
    @Override
    public List<Permission> getRolePermissions(Long roleId) {
        return baseMapper.selectRolePermissions(roleId);
    }
    

    
    @Override
    public List<MenuTree> getUserMenuTree(Long userId) {
        List<Permission> permissions = getUserPermissions(userId);
        return treeBuilder.buildTree(permissions);
    }
    
    @Override
    public List<MenuTree> getAllMenuTree() {
        List<Permission> permissions = list(new LambdaQueryWrapper<Permission>()
                .eq(Permission::getStatus, 1)
                .orderByAsc(Permission::getSort));
        return treeBuilder.buildTree(permissions);
    }
    
    @Override
    public List<Permission> buildPermissionTree() {
        List<Permission> permissions = list(new LambdaQueryWrapper<Permission>()
                .orderByAsc(Permission::getSort));
        
        // 构建树形结构
        Map<Long, List<Permission>> parentMap = permissions.stream()
                .collect(Collectors.groupingBy(Permission::getParentId));
        
        // 设置子节点
        permissions.forEach(permission -> {
            permission.setChildren(parentMap.get(permission.getId()));
        });
        
        // 返回顶级节点
        return permissions.stream()
                .filter(permission -> permission.getParentId() == 0)
                .collect(Collectors.toList());
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void createPermission(PermissionDTO permissionDTO) {
        // 1. 检查权限标识是否存在
        if (checkPermissionCodeExists(permissionDTO.getCode())) {
            throw new BusinessException(ResultCode.PERMISSION_CODE_EXISTS);
        }
        
        // 2. 创建权限
        Permission permission = new Permission();
        permission.setParentId(permissionDTO.getParentId() != null ? permissionDTO.getParentId() : 0L);
        permission.setName(permissionDTO.getName());
        permission.setCode(permissionDTO.getCode());
        permission.setType(permissionDTO.getType());
        permission.setPath(permissionDTO.getPath());
        permission.setComponent(permissionDTO.getComponent());
        permission.setIcon(permissionDTO.getIcon());
        permission.setSort(permissionDTO.getSort() != null ? permissionDTO.getSort() : 0);
        permission.setStatus(permissionDTO.getStatus() != null ? permissionDTO.getStatus() : 1);
        
        if (!save(permission)) {
            throw new BusinessException(ResultCode.FAILED);
        }
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updatePermission(PermissionDTO permissionDTO) {
        // 1. 检查权限是否存在
        Permission existingPermission = getById(permissionDTO.getId());
        if (existingPermission == null) {
            throw new BusinessException(ResultCode.PERMISSION_NOT_FOUND);
        }
        
        // 2. 如果修改了权限标识，检查是否存在
        if (!existingPermission.getCode().equals(permissionDTO.getCode()) 
                && checkPermissionCodeExists(permissionDTO.getCode())) {
            throw new BusinessException(ResultCode.PERMISSION_CODE_EXISTS);
        }
        
        // 3. 更新权限
        Permission permission = new Permission();
        permission.setId(permissionDTO.getId());
        permission.setName(permissionDTO.getName());
        permission.setCode(permissionDTO.getCode());
        permission.setType(permissionDTO.getType());
        permission.setPath(permissionDTO.getPath());
        permission.setComponent(permissionDTO.getComponent());
        permission.setIcon(permissionDTO.getIcon());
        permission.setSort(permissionDTO.getSort());
        permission.setStatus(permissionDTO.getStatus());
        
        if (!updateById(permission)) {
            throw new BusinessException(ResultCode.FAILED);
        }
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deletePermission(Long id) {
        // 1. 检查是否有子权限
        if (count(new LambdaQueryWrapper<Permission>()
                .eq(Permission::getParentId, id)) > 0) {
            throw new BusinessException(ResultCode.PERMISSION_HAS_CHILDREN);
        }
        
        // 2. 删除角色权限关联
        rolePermissionMapper.delete(new LambdaQueryWrapper<RolePermission>()
                .eq(RolePermission::getPermissionId, id));
        
        // 3. 删除权限
        if (!removeById(id)) {
            throw new BusinessException(ResultCode.FAILED);
        }
    }
    
    /**
     * 检查权限标识是否存在
     */
    private boolean checkPermissionCodeExists(String code) {
        return count(new LambdaQueryWrapper<Permission>()
                .eq(Permission::getCode, code)) > 0;
    }
} 